package com.quzubuluo.quzutool;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.quzubuluo.quzutool.zxing.CaptureActivity;
import com.quzubuluo.quzutool.base.BaseResponse;
import com.quzubuluo.quzutool.model.InputDataRemoteSource;
import com.quzubuluo.quzutool.model.InputReposity;
import com.quzubuluo.quzutool.net.BaseObserver;
import com.quzubuluo.quzutool.net.RxManage;
import com.quzubuluo.quzutool.net.RxSchedulers;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private final static int IMAGE_PICK = 100;
    private boolean hasPermission = false;
    private ImageView ivFirst;
    private int choosePosition = 0;
    public static Uri uriOne;
    public static Uri uriTwo;
    public static Uri uriThree;
    private TextView etName;
    private EditText etPhone;
    private EditText etAddress;
    private EditText etId;
    private EditText etImei;
    private Spinner spType;
    private Spinner spColor;
    private Spinner spStorage;
    private ImageView ivSecond;
    private ImageView ivThird;
    private ImageView ivOneDel;
    private ImageView ivTwoDel;
    private ImageView ivThreeDel;
    private final int SCAN_INFO = 101;
    private boolean bOneShow;
    private boolean bTwoShow;
    private boolean bThreeShow;
    private EditText etExpress;
    private EditText etAmount;
    private RxManage rxManage = new RxManage();
    private InputReposity reposity;
    private String pathOne = "", pathTwo = "", pathThree = "";
    private TextView etYear;
    private TextView etMonth;
    private TextView etDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.cl_1f));
        }
        initView();
        reposity = InputReposity.getInstance(new InputDataRemoteSource());
    }

    private void initView() {
        etYear = (TextView) findViewById(R.id.et_year);
        etMonth = (TextView) findViewById(R.id.et_month);
        etDate = (TextView) findViewById(R.id.et_date);
        Calendar calendar = Calendar.getInstance();
        etYear.setText(calendar.get(Calendar.YEAR) + "");
        etMonth.setText((calendar.get(Calendar.MONTH) + 1) + "");
        etDate.setText(calendar.get(Calendar.DATE) + "");
        findViewById(R.id.iv_scan).setOnClickListener(this);
        findViewById(R.id.tv_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });
        etName = (TextView) findViewById(R.id.et_name);
        etPhone = (EditText) findViewById(R.id.et_phone);
        etAddress = (EditText) findViewById(R.id.et_address);
        etId = (EditText) findViewById(R.id.et_id);
        etExpress = (EditText) findViewById(R.id.et_express);
        etAmount = (EditText) findViewById(R.id.et_amount);
        etImei = (EditText) findViewById(R.id.et_imei);
        spType = (Spinner) findViewById(R.id.sp_phone_type);
        spColor = (Spinner) findViewById(R.id.sp_phone_color);
        spStorage = (Spinner) findViewById(R.id.sp_phone_storage);
        spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String string = spType.getSelectedItem().toString();
                if (string.contains("7")) {
                    spColor.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.item_spinner,//每一项的布局
                            getResources().getStringArray(R.array.iphone7_colors)));
                    spStorage.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.item_spinner,//每一项的布局
                            getResources().getStringArray(R.array.phone7_storages)));
                } else {
                    spColor.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.item_spinner,//每一项的布局
                            getResources().getStringArray(R.array.iphone6_colors)));
                    spStorage.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.item_spinner,//每一项的布局
                            getResources().getStringArray(R.array.phone6_storages)));
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spStorage.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String storage = spStorage.getSelectedItem().toString();
                String type = spType.getSelectedItem().toString();
                if (storage.contains("32") || type.contains("6")) {
                    spColor.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.item_spinner,//每一项的布局
                            getResources().getStringArray(R.array.iphone7_colors)));
                } else {
                    spColor.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.item_spinner,//每一项的布局
                            getResources().getStringArray(R.array.iphone7_big_colors)));
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        ivFirst = (ImageView) findViewById(R.id.iv_first);
        ivOneDel = (ImageView) findViewById(R.id.iv_one_del);
        ivOneDel.setOnClickListener(this);
        ivFirst.setOnClickListener(this);
        ivSecond = (ImageView) findViewById(R.id.iv_second);
        ivTwoDel = (ImageView) findViewById(R.id.iv_two_del);
        ivTwoDel.setOnClickListener(this);
        ivSecond.setOnClickListener(this);
        ivThird = (ImageView) findViewById(R.id.iv_third);
        ivThreeDel = (ImageView) findViewById(R.id.iv_three_del);
        ivThreeDel.setOnClickListener(this);
        ivThird.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestPermission();
    }

    @Override
    public void onClick(View view) {
        if (!hasPermission) {
            requestPermission();
            return;
        }
        switch (view.getId()) {
            case R.id.iv_scan:
                startActivityForResult(new Intent(MainActivity.this, CaptureActivity.class), SCAN_INFO);
                break;
            case R.id.iv_first:
                if (bOneShow) {
                    Intent intent = new Intent(MainActivity.this, ShowImageActivity.class);
                    intent.putExtra("uri", uriOne);
                    startShowImg(intent);
                } else {
                    choosePosition = 1;
                    choosePicture();
                }
                break;
            case R.id.iv_second:
                if (bTwoShow) {
                    Intent intent = new Intent(MainActivity.this, ShowImageActivity.class);
                    intent.putExtra("uri", uriTwo);
                    startShowImg(intent);
                } else {
                    choosePosition = 2;
                    choosePicture();
                }
                break;
            case R.id.iv_third:
                if (!hasPermission) {
                    requestPermission();
                    return;
                }
                if (bThreeShow) {
                    Intent intent = new Intent(MainActivity.this, ShowImageActivity.class);
                    intent.putExtra("uri", uriThree);
                    startShowImg(intent);
                } else {
                    choosePosition = 3;
                    choosePicture();
                }
                break;
            case R.id.iv_one_del:
                ivFirst.setImageResource(R.drawable.add_picture);
                ivOneDel.setVisibility(View.GONE);
                uriOne = null;
                bOneShow = false;
                break;
            case R.id.iv_two_del:
                ivSecond.setImageResource(R.drawable.add_picture);
                ivTwoDel.setVisibility(View.GONE);
                bTwoShow = false;
                uriTwo = null;
                break;
            case R.id.iv_three_del:
                ivThird.setImageResource(R.drawable.add_picture);
                ivThreeDel.setVisibility(View.GONE);
                bThreeShow = false;
                uriThree = null;
                break;
        }
    }

    private void startShowImg(Intent intent) {
        startActivity(intent);
    }

    private void choosePicture() {
        Matisse.from(MainActivity.this)
                .choose(MimeType.ofAll())
                .theme(R.style.Matisse_Dracula)
                .countable(false)
                .maxSelectable(1)
                .capture(true)
                .captureStrategy(new CaptureStrategy(true, "com.quzubuluo.tool.fileprovider"))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(IMAGE_PICK);
    }

    private void submit() {
        String name = etName.getText().toString();
        String phone = etPhone.getText().toString();
        String address = etAddress.getText().toString();
        String id = etId.getText().toString().toUpperCase();
        String imei = etImei.getText().toString();
        if (TextUtils.isEmpty(imei)) {
            Toast.makeText(this, "IMEI不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        String year = etYear.getText().toString();
        String month = etMonth.getText().toString();
        String date = etDate.getText().toString();
        if (TextUtils.isEmpty(year) || TextUtils.isEmpty(month) || TextUtils.isEmpty(date) || year.length() < 4) {
            Toast.makeText(this, "请填写正确的发货时间", Toast.LENGTH_SHORT).show();
            return;
        }
        String phoneType = spType.getSelectedItem().toString();
        String phoneColor = spColor.getSelectedItem().toString();
        String phoneStorage = spStorage.getSelectedItem().toString();
        String goodAmount = etAmount.getText().toString();
        if (TextUtils.isEmpty(goodAmount)) {
            Toast.makeText(this, "请填写商品价格", Toast.LENGTH_SHORT).show();
            return;
        }
        String express = etExpress.getText().toString();
        input(name, phone, address, id, imei, phoneType, phoneColor, phoneStorage, goodAmount, express, year + "-" + month + "-" + date);
    }

    private void input(String name, String phone, String address, String id, String imei, String phoneType, String phoneColor, String phoneStorage, String goodAmount, String express, String shippingTime) {
        Map<String, RequestBody> picFiles = new HashMap<>();
        final LoadingDialog loadingDialog = new LoadingDialog(this);
        loadingDialog.show();
        if (uriOne != null) {
            File fileOne = new File(pathOne);
            if (fileOne.exists()) {
                RequestBody fileOneBody = RequestBody.create(MediaType.parse("image/*"), fileOne);
                picFiles.put("picFiles\"; filename=\"" + fileOne.getName() + ".png", fileOneBody);
            }
//            requestImgPart = MultipartBody.Part.createFormData("picFiles", fileOne.getName(), requestImgFile);
        }
        if (uriTwo != null) {
            File fileTwo = new File(pathTwo);
            if (fileTwo.exists()) {
                RequestBody fileTwoBody = RequestBody.create(MediaType.parse("image/*"), fileTwo);
                picFiles.put("picFiles\"; filename=\"" + fileTwo.getName() + ".png", fileTwoBody);
            }
//            requestImgPart = MultipartBody.Part.createFormData("picFiles", fileTwo.getName(), requestImgFile);
        }
        if (uriThree != null) {
            File fileThree = new File(pathThree);
            if (fileThree.exists()) {
                RequestBody fileThreeBody = RequestBody.create(MediaType.parse("image/*"), fileThree);
                picFiles.put("picFiles\"; filename=\"" + fileThree.getName() + ".png", fileThreeBody);
            }
//            requestImgPart = MultipartBody.Part.createFormData("picFiles", fileThree.getName(), requestImgFile);
        }
        if (picFiles.isEmpty()) {
            reposity.inputInfo(name, phone, address, id, imei, phoneType, phoneColor, phoneStorage, goodAmount, "haoke", express,
                    shippingTime)
                    .compose(RxSchedulers.<BaseResponse>io_main())
                    .subscribe(new BaseObserver<BaseResponse>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            rxManage.add(d);
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            Log.i("chen", "onError: " + e.getLocalizedMessage());
                            loadingDialog.loadFailed();
                        }

                        @Override
                        public void onComplete() {
                            super.onComplete();
                            loadingDialog.close();
                        }

                        @Override
                        public void onNext(BaseResponse value) {
                            loadingDialog.loadSuccess();
                            if (value.getResult() == 0) {
                                Toast.makeText(MainActivity.this, "录入成功，辛苦啦!", Toast.LENGTH_SHORT).show();
                                clearInput();
                            } else {
                                Log.i("chen", "onNext: " + value.getMsg());
                                Toast.makeText(MainActivity.this, "" + value.getMsg(), Toast.LENGTH_SHORT).show();
                            }

                        }
                    });
        } else {
            reposity.inputInfo(name, phone, address, id, imei, phoneType, phoneColor, phoneStorage, goodAmount, "haoke", express,
                    shippingTime, picFiles)
                    .compose(RxSchedulers.<BaseResponse>io_main())
                    .subscribe(new BaseObserver<BaseResponse>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            rxManage.add(d);
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            Log.i("chen", "onError: " + e.getLocalizedMessage());
                            loadingDialog.loadFailed();
                        }

                        @Override
                        public void onComplete() {
                            super.onComplete();
                            loadingDialog.close();
                        }

                        @Override
                        public void onNext(BaseResponse value) {
                            loadingDialog.loadSuccess();
                            if (value.getResult() == 0) {
                                Toast.makeText(MainActivity.this, "录入成功，辛苦啦!", Toast.LENGTH_SHORT).show();
                                clearInput();
                            } else {
                                Toast.makeText(MainActivity.this, "" + value.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }

    }

    private void clearInput() {
        etName.setText("");
        etPhone.setText("");
        etAddress.setText("");
        etId.setText("");
        etExpress.setText("");
        etImei.setText("");
        etAmount.setText("");
        if (ivOneDel.getVisibility() == View.VISIBLE) {
            ivOneDel.performClick();
        }
        if (ivTwoDel.getVisibility() == View.VISIBLE) {
            ivTwoDel.performClick();
        }
        if (ivThreeDel.getVisibility() == View.VISIBLE) {
            ivThreeDel.performClick();
        }
    }

    private void requestPermission() {
        new RxPermissions(this).request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean accept) throws Exception {
                        if (accept) {
                            hasPermission = true;
                        } else {
                            hasPermission = false;
                        }
                    }
                });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        rxManage.clear();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IMAGE_PICK && resultCode == RESULT_OK) {
            Uri uri = Matisse.obtainResult(data).get(0);
            switch (choosePosition) {
                case 1:
                    Glide.with(this).load(uri).asBitmap().into(ivFirst);
                    ivOneDel.setVisibility(View.VISIBLE);
                    bOneShow = true;
                    pathOne = Matisse.obtainPathResult(data).get(0);
                    uriOne = uri;
                    break;
                case 2:
                    Glide.with(this).load(uri).asBitmap().into(ivSecond);
                    ivTwoDel.setVisibility(View.VISIBLE);
                    bTwoShow = true;
                    uriTwo = uri;
                    pathTwo = Matisse.obtainPathResult(data).get(0);
                    break;
                case 3:
                    Glide.with(this).load(uri).asBitmap().into(ivThird);
                    ivThreeDel.setVisibility(View.VISIBLE);
                    bThreeShow = true;
                    uriThree = uri;
                    pathThree = Matisse.obtainPathResult(data).get(0);
                    break;
            }
            choosePosition = 0;
        } else if (requestCode == SCAN_INFO && resultCode == RESULT_OK) {
            String scanCode = data.getStringExtra("scanCode");
            etImei.setText(scanCode);
            etImei.clearFocus();
        }
    }

}